<div class="chart-container">  
    <canvas id="{{ chart_id|default:'pieChart' }}" height="{{ height|default:250 }}"></canvas>  
</div>  

<script>  
document.addEventListener('DOMContentLoaded', function() {  
    const ctx = document.getElementById('{{ chart_id|default:"pieChart" }}').getContext('2d');  
    
    // 数据准备  
    {% if data %}  
        // 如果提供了data变量，使用data变量  
        const labels = [{% for item in data %}'{{ item.name }}',{% endfor %}];  
        const values = [{% for item in data %}{{ item.value }},{% endfor %}];  
    {% else %}  
        // 否则使用wallets变量  
        const labels = [{% for wallet in wallets %}'{{ wallet.name }}',{% endfor %}];  
        const values = [{% for wallet in wallets %}{{ wallet.current_balance }},{% endfor %}];  
    {% endif %}  
    
    const backgroundColors = [  
        '#4e73df', '#1cc88a', '#36b9cc', '#f6c23e', '#e74a3b', '#858796',  
        '#5a5c69', '#6610f2', '#6f42c1', '#fd7e14', '#20c997', '#17a2b8'  
    ];  
    
    // 创建图表  
    new Chart(ctx, {  
        type: 'pie',  
        data: {  
            labels: labels,  
            datasets: [{  
                data: values,  
                backgroundColor: backgroundColors,  
                hoverBackgroundColor: backgroundColors.map(color => color + 'dd'),  
                hoverBorderColor: 'rgba(234, 236, 244, 1)',  
            }],  
        },  
        options: {  
            maintainAspectRatio: false,  
            tooltips: {  
                callbacks: {  
                    label: function(tooltipItem, data) {  
                        const dataset = data.datasets[tooltipItem.datasetIndex];  
                        const total = dataset.data.reduce((previousValue, currentValue) => previousValue + currentValue);  
                        const currentValue = dataset.data[tooltipItem.index];  
                        const percentage = Math.round((currentValue/total) * 100);  
                        return `${data.labels[tooltipItem.index]}: ¥${currentValue.toFixed(2)} (${percentage}%)`;  
                    }  
                }  
            },  
            legend: {  
                display: true,  
                position: 'right',  
            },  
            title: {  
                display: {% if title %}true{% else %}false{% endif %},  
                text: '{{ title|default:"" }}',  
                fontSize: 16  
            },  
            responsive: true  
        }  
    });  
});  
</script>